#ifndef __comm_hpp__
#define __comm_hpp__

#define PATHNAME "./"
#define POOJD 0x6666

#include<sys/types.h>
#include<sys/ipc.h>
#include<errno.h>
#include<string.h>
#include<iostream>
#include<sys/shm.h>
#include<sys/stat.h>
#include<assert.h>
#include<unistd.h>
using namespace std;

const int gsize = 4096;

key_t GetKey()
{
  key_t key = ftok(PATHNAME,POOJD);
  if(key == -1)
  {
    cout << "errno : " << errno << " "  << strerror(errno) << endl;
    exit(1);
  }
  return key;
}

string toHex(key_t key)
{
  char str[64];
  snprintf(str,sizeof(str),"%x",key);
  return str;
}

int CreatShmHelper(key_t key,int size,int flag)
{
  int shm = shmget(key,size,flag);
  if(shm == -1)
  {
    cout << "errno : " << errno << " " << strerror(errno) << endl;
    exit(2);
  }
  return shm;
}

int CreatShm(key_t key,int size)
{
  umask(0);
  int shmid = CreatShmHelper(key,size,IPC_CREAT | IPC_EXCL | 0664);
  if(shmid < 0){
    perror("create shmid\n");
    return -1;
  }
  return shmid;
}

int Getshm(key_t key,int size)
{
  return CreatShmHelper(key,size,IPC_CREAT);
}

char* AttachShm(int shmid)
{
  char* Start = (char*)shmat(shmid,nullptr,0);
  return Start;
}

void DetachAttach(char* Start)
{
  int n = shmdt(Start);
  (void)n;
  assert(n != -1);
  return;
}

void DeleteShm(int shmid)
{
  int n = shmctl(shmid,IPC_RMID,nullptr);
  (void)n;
  assert(n != -1);
  return;
}

#endif
